package com.tanhua.manager.service;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.manager.domain.AnalysisByDay;
import com.tanhua.manager.domain.Log;
import com.tanhua.manager.mapper.AnalysisMapper;
import com.tanhua.manager.mapper.LogMapper;
import com.tanhua.manager.utils.ComputeUtil;
import com.tanhua.manager.vo.AnalysisChartDataItem;
import com.tanhua.manager.vo.AnalysisSummaryVO;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class AnalysisService {
    @Autowired
    private AnalysisMapper analysisMapper;
    @Autowired
    private LogMapper logMapper;
    /**
     * 首页-概要信息统计
     */
    public ResponseEntity summary() {
        AnalysisSummaryVO vo = new AnalysisSummaryVO();

        //1. 累计用户数
        long cumulativeUsers = analysisMapper.cumulativeUsers();
        vo.setCumulativeUsers(cumulativeUsers);

        //2. 过去30天活跃用户数
        Date today = DateUtil.beginOfDay(new Date());
        DateTime date30 = DateUtil.offsetDay(today, -30);
        long activeUsers30 = analysisMapper.queryActiveUsers(date30, today);
        vo.setActivePassMonth(activeUsers30);

        //3. 过去7天活跃用户数
        DateTime date7 = DateUtil.offsetDay(today, -7);
        long activeUsers7 = analysisMapper.queryActiveUsers(date7, today);
        vo.setActivePassWeek(activeUsers7);

        //4. 今日新增用户数
        AnalysisByDay analysisToday = analysisMapper.selectOne(new LambdaQueryWrapper<AnalysisByDay>().eq(AnalysisByDay::getRecordDate, today));
        Integer newUsersToday = analysisToday.getNumRegistered();
        vo.setNewUsersToday(newUsersToday.longValue());

        //5. 今日新增用户涨跌率
        //5.1 查询昨天新增用户数
        DateTime yesterday = DateUtil.offsetDay(today, -1);
        AnalysisByDay analysisYesterday = analysisMapper.selectOne(new LambdaQueryWrapper<AnalysisByDay>().eq(AnalysisByDay::getRecordDate, yesterday));
        Integer newUserYesterday = analysisYesterday.getNumRegistered();
        //5.2 计算今日新增用户涨跌率
        BigDecimal newUsersTodayRate = ComputeUtil.computeRate(newUsersToday.longValue(), newUserYesterday.longValue());
        vo.setNewUsersTodayRate(newUsersTodayRate);

        //6. 今日登录次数
        vo.setLoginTimesToday(analysisToday.getNumLogin().longValue());

        //7. 今日登录次数涨跌率
        BigDecimal loginTimesTodayRate = ComputeUtil.computeRate(analysisToday.getNumLogin().longValue(), analysisYesterday.getNumLogin().longValue());
        vo.setLoginTimesTodayRate(loginTimesTodayRate);

        //8. 今日活跃用户数
        vo.setActiveUsersToday(analysisToday.getNumActive().longValue());

        //9. 今日活跃用户涨跌率
        BigDecimal activeUsersTodayRate = ComputeUtil.computeRate(analysisToday.getNumActive().longValue(), analysisYesterday.getNumActive().longValue());
        vo.setActiveUsersTodayRate(activeUsersTodayRate);

        return ResponseEntity.ok(vo);
    }

    public ResponseEntity usersCharData(Long sd, Long ed, Integer type) {

        //1. 今年的数据： 指定时间范围内，每天的 新增用户数/活跃用户数/次日留存数
        DateTime startThisYear = DateUtil.beginOfDay(DateUtil.date(sd));
        DateTime endThisYear = DateUtil.endOfDay(DateUtil.date(ed));

        List<AnalysisByDay> thisYearAnalysisList = analysisMapper.selectList(new LambdaQueryWrapper<AnalysisByDay>().between(AnalysisByDay::getRecordDate, startThisYear, endThisYear));
        List<AnalysisChartDataItem> thisYearItemList = new ArrayList<>();
        for (AnalysisByDay analysis : thisYearAnalysisList) {
            AnalysisChartDataItem item = new AnalysisChartDataItem();
            item.setTitle(DateUtil.format(analysis.getRecordDate(), "yyyy-MM-dd"));
            if (type == 101) {
                item.setAmount(analysis.getNumRegistered().longValue());
            } else if (type == 102) {
                item.setAmount(analysis.getNumActive().longValue());
            } else if (type == 103) {
                item.setAmount(analysis.getNumRetention1d().longValue());
            }
            thisYearItemList.add(item);
        }

        //2. 去年的数据： 指定时间范围内，每天的 新增用户数/活跃用户数/次日留存数
        DateTime startLastYear = DateUtil.offset(startThisYear, DateField.YEAR, -1);
        DateTime endLastYear = DateUtil.offset(endThisYear, DateField.YEAR, -1);

        List<AnalysisByDay> lastYearAnalysisList = analysisMapper.selectList(new LambdaQueryWrapper<AnalysisByDay>().between(AnalysisByDay::getRecordDate, startLastYear, endLastYear));
        List<AnalysisChartDataItem> lastYearItemList = new ArrayList<>();
        for (AnalysisByDay analysis : lastYearAnalysisList) {
            AnalysisChartDataItem item = new AnalysisChartDataItem();
            item.setTitle(DateUtil.format(analysis.getRecordDate(), "yyyy-MM-dd"));
            if (type == 101) {
                item.setAmount(analysis.getNumRegistered().longValue());
            } else if (type == 102) {
                item.setAmount(analysis.getNumActive().longValue());
            } else if (type == 103) {
                item.setAmount(analysis.getNumRetention1d().longValue());
            }
            lastYearItemList.add(item);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("thisYear", thisYearItemList);
        result.put("lastYear", lastYearItemList);

        return ResponseEntity.ok(result);

    }

    public void analysis() {

        //准备统计日期
        Date now = new Date();
        String today = DateUtil.format(now, "yyyy-MM-dd");

        //如果不存在统计结果 就创建一条
        String yesterday = DateUtil.offsetDay(now, -1).toString("yyyy-MM-dd");
        AnalysisByDay analysis = analysisMapper.selectOne(new LambdaQueryWrapper<AnalysisByDay>().eq(AnalysisByDay::getRecordDate, today));
        if (analysis == null) {
            analysis = new AnalysisByDay();
            analysis.setRecordDate(now);
            analysis.setCreated(now);
            analysis.setUpdated(now);

            analysisMapper.insert(analysis);
        }
        //统计数据
        //今日新增数据
        QueryWrapper<Log> wrapper = new QueryWrapper<>();
        wrapper.eq("TYPE", "0102");
        wrapper.eq("log_time", today);
        Integer register = logMapper.selectCount(wrapper);
        analysis.setNumRegistered(register);

        //3.2 今日登录次数
        wrapper = new QueryWrapper<>();
        wrapper.eq("TYPE", "0101");
        wrapper.eq("log_time", today);
        Integer login = logMapper.selectCount(wrapper);
        analysis.setNumLogin(login);

        //3.3 今日活跃用户数
        wrapper = new QueryWrapper<>();
        wrapper.eq("log_time", today);
        wrapper.select("distinct user_id");
        Integer active = logMapper.selectCount(wrapper);
        analysis.setNumActive(active);

        //3.4 次日留存用户数
        int retention = logMapper.queryRetentionCount(today, yesterday);
        analysis.setNumRetention1d(retention);

        //4. 更新到数据库
        analysisMapper.updateById(analysis);


    }
}